package com.cx.base.day13_io.io_08_dataStream;

import java.io.*;

/**
 * 之前的ObjectStream实现引用类型的序列化
 * 而 DataStream 实现基本数据类型、字符串和byte[]的序列化
 *
 * @Author: robert.song
 * @Date: Created in 2022/4/23
 */
public class DataStream {

    public static void main(String[] args) throws IOException {
//        将基本数据类型和字符串按照顺序写入文本
//        字符串只允许utf8格式
        dataOutputStream();
//        从文本读取按照顺序将数据读出
        dataInputStream();
    }

    public static void dataOutputStream() throws IOException {
        DataOutputStream dos = null;
        File file = new File("." + System.getProperty("file.separator") + "data.txt");
        file.getParentFile().mkdirs();
        file.createNewFile();
        try {
            dos = new DataOutputStream(new FileOutputStream(file));
            dos.writeUTF("汤姆");
            dos.flush();
            dos.writeInt(20);
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null)
                    dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //将文件中储存的基本数据类型变量和字符串读取到内存中，保存到变量
//    必须按照写的顺序读取
    public static void dataInputStream() {
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream(new File("." + System.getProperty("file.separator") + "data.txt")));
            String name = dis.readUTF();
            int age = dis.readInt();
            System.out.println("name = " + name);
            System.out.println("age = " + age);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
